package com.yjyw.tiexie.common.net;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


import com.google.gson.Gson;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.StringUtil;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * @author Administrator
 */
public class OkHttpUtil {

    private static String sessionid = "";

    public static String serviceId = "";

    public static String token = "";


    public static void setServiceId(String serviceId) {
        OkHttpUtil.serviceId = serviceId;
    }

    public static String getServiceId() {
        return serviceId;
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private int type;//0post


    public static Observable<String> getResult(final NetRequest request, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {

//                    JSONObject json = new JSONObject(request.params);
//                    Log.e("tag-===", json.toString());
//                    RequestBody body = RequestBody.create(JSON, json.toString());
//                    Request.Builder builder = new Request.Builder().url(request.url).post(body);

                    //map转json
//                    Request.Builder builder;
//                    if (request.params != null && !request.params.isEmpty()) {
////                        JSONObject json = new JSONObject(request.params);
////                        RequestBody body = RequestBody.create(JSON, json.toString());
//                        RequestBody body = RequestBody.create(JSON, mapToJson(request.params));
//                        LogUtil.e("json:", mapToJson(request.params));
//                        builder = new Request.Builder().url(request.url).post(body);
//                    } else {
//                        FormBody.Builder f = new FormBody.Builder();
//                        builder = new Request.Builder().url(request.url).post(f.build());
//                    }

                    FormBody.Builder f = new FormBody.Builder();
                    if (request.params != null && !request.params.isEmpty()) {
                        for (String key : request.params.keySet()) {
                            f.add(key, String.valueOf(request.params.get(key)));
                        }
                    }
                    Request.Builder builder = new Request.Builder().url(request.url).post(f.build());

                    SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
//                    除了登录之前接口用临时token,其它用登录成功token
                    if (HandlerCode.LOGIN == request.requestCode ||
                            HandlerCode.SEND_MESSAGE_REGISTER == request.requestCode) {
                        //获得登录手机号
                        token = sp.getString("onceToken", "");
                        builder.addHeader("X-Token", "" + token);
                    } else {
                        //获得登录手机号
                        token = sp.getString("token", "");
                        if (StringUtil.isEmpty(token)) {
                            token = sp.getString("onceToken", "");
                            builder.addHeader("X-Token", "" + token);
                        } else {
                            builder.addHeader("X-Token", "" + token);
                        }
                    }
                    LogUtil.e("token", token);


//                    //添加请求头
                    String jpushReisID = JPushInterface.getRegistrationID(activity);
                    LogUtil.e("jpushReisID", jpushReisID + "");
                    builder.addHeader("Content-Type", "application/json");

                    Request mRequest = builder.build();
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }

    public static Observable<String> getResultBean(final NetRequest request, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {

                    //map转json
                    Request.Builder builder;
                    if (request.params != null && !request.params.isEmpty()) {
                        RequestBody body = RequestBody.create(JSON, mapToJson(request.params));
                        LogUtil.e("json:", mapToJson(request.params));
                        builder = new Request.Builder().url(request.url).post(body);
                    } else {
                        FormBody.Builder f = new FormBody.Builder();
                        builder = new Request.Builder().url(request.url).post(f.build());
                    }


                    SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
//                    除了登录之前接口用临时token,其它用登录成功token
                    if (HandlerCode.LOGIN == request.requestCode ||
                            HandlerCode.SEND_MESSAGE_REGISTER == request.requestCode) {
                        //获得登录手机号
                        token = sp.getString("onceToken", "");
                        builder.addHeader("X-Token", "" + token);
                    } else {
                        //获得登录手机号
                        token = sp.getString("token", "");
                        if (StringUtil.isEmpty(token)) {
                            token = sp.getString("onceToken", "");
                            builder.addHeader("X-Token", "" + token);
                        } else {
                            builder.addHeader("X-Token", "" + token);
                        }
                    }
                    LogUtil.e("token", token);

//                    //添加请求头
                    String jpushReisID = JPushInterface.getRegistrationID(activity);
                    LogUtil.e("jpushReisID", jpushReisID + "");
                    builder.addHeader("Content-Type", "application/json");

                    Request mRequest = builder.build();
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }

    public static Observable<String> getPutResultBean(final NetRequest request, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {

                    //map转json
                    Request.Builder builder;
                    if (request.params != null && !request.params.isEmpty()) {
                        RequestBody body = RequestBody.create(JSON, mapToJson(request.params));
                        LogUtil.e("json:", mapToJson(request.params));
                        builder = new Request.Builder().url(request.url).put(body);
                    } else {
                        FormBody.Builder f = new FormBody.Builder();
                        builder = new Request.Builder().url(request.url).put(f.build());
                    }


                    SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
//                    除了登录之前接口用临时token,其它用登录成功token
                    if (HandlerCode.LOGIN == request.requestCode ||
                            HandlerCode.SEND_MESSAGE_REGISTER == request.requestCode) {
                        //获得登录手机号
                        token = sp.getString("onceToken", "");
                        builder.addHeader("X-Token", "" + token);
                    } else {
                        //获得登录手机号
                        token = sp.getString("token", "");
                        if (StringUtil.isEmpty(token)) {
                            token = sp.getString("onceToken", "");
                            builder.addHeader("X-Token", "" + token);
                        } else {
                            builder.addHeader("X-Token", "" + token);
                        }
                    }
                    LogUtil.e("token", token);

//                    //添加请求头
                    String jpushReisID = JPushInterface.getRegistrationID(activity);
                    LogUtil.e("jpushReisID", jpushReisID + "");
                    builder.addHeader("Content-Type", "application/json");
                    Request mRequest = builder.build();
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 将Map转化为Json
     *
     * @param map
     * @return String
     */
    public static <T> String mapToJson(Map<String, T> map) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);
        return jsonStr;
    }

    /**
     * get请求
     *
     * @param request
     * @param activity
     * @return
     * @throws Exception
     */
    public static Observable<String> getResultGet(final NetRequest request, final Context activity) throws Exception {//get
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    Request.Builder builder = new Request.Builder();
                    String finalUrl = getAppendUrl(request.url, request.params);

                    //除了登录接口不需要token,其它接口都需要token
                    if (HandlerCode.LOGIN != request.requestCode) {
                        SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
                        //获得登录手机号
                        token = sp.getString("token", "");
                        if (StringUtil.isEmpty(token)) {
                            token = sp.getString("onceToken", "");
                            builder.addHeader("X-Token", "" + token);
                        } else {
                            builder.addHeader("X-Token", "" + token);
                        }
                    }

                    //添加请求头
                    builder.addHeader("Content-Type", "application/json");


                    OkHttpClient client ;
                    OkHttpClient.Builder builderOk = new OkHttpClient.Builder();
//                    builderOk.sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
//                            .hostnameVerifier(SSLSocketClient.getHostnameVerifier());

//                    builderOk.hostnameVerifier(new AllowAllHostnameVerifier());
                    client = builderOk.build();

                    Request mRequest = builder.get().url(finalUrl).build();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }

    private static final MediaType FROM_DATA = MediaType.parse("multipart/form-data");

    public static Observable<String> getResultFile(final NetRequest request, final File file, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {

                    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

                    MultipartBody.Builder f = new MultipartBody.Builder();
                    f.setType(FROM_DATA);
                    f.addFormDataPart("file", file.getName() + "", fileBody);
                    if (request.params != null && !request.params.isEmpty()) {
                        for (String key : request.params.keySet()) {

                            f.addFormDataPart(key, String.valueOf(request.params.get(key)));
                        }
                    }

                    Request.Builder builder = new Request.Builder().url(request.url).post(f.build());
                    //除了登录接口不需要token,其它接口都需要token
                    SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
                    //获得登录手机号
                    token = sp.getString("token", "");
                    if (StringUtil.isEmpty(token)) {
                        token = sp.getString("onceToken", "");
                        builder.addHeader("X-Token", "" + token);
                    } else {
                        builder.addHeader("X-Token", "" + token);
                    }

                    builder.addHeader("Content-Type", "application/json");

                    Request mRequest = builder.build();
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }


    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static Observable<String> getResultFileList(final NetRequest request, final String pic_key, final List<File> files, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {


                    MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
                    multipartBodyBuilder.setType(MultipartBody.FORM);
                    //遍历map中所有参数到builder
                    if (request.params != null) {
                        for (String key : request.params.keySet()) {
                            multipartBodyBuilder.addFormDataPart(key, (String) request.params.get(key));
                        }
                    }


                    for (int i = 0; i < files.size(); i++) {
                        multipartBodyBuilder.addFormDataPart("img" + (i + 1), files.get(i).getName(), RequestBody.create(MEDIA_TYPE_PNG, files.get(i)));
                    }

//                    //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
//                    if (files != null) {
//                        for (File file : files) {
//                            multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
//                        }
//                    }
                    //构建请求体
                    RequestBody requestBody = multipartBodyBuilder.build();
                    Request.Builder RequestBuilder = new Request.Builder();
                    // 添加URL地址
                    RequestBuilder.url(request.url);
                    RequestBuilder.post(requestBody);
                    Request request = RequestBuilder.build();


                    OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
                            .readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
                            .build();
                    client.newCall(request).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }


    /**
     * delete
     *
     * @param request
     * @param activity
     * @return
     * @throws Exception
     */

    public static Observable<String> getDeleteResult(final NetRequest request, final Context activity) throws Exception {//post
        return Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {

                    String finalUrl = getAppendUrl(request.url, request.params);

                    FormBody.Builder f = new FormBody.Builder();
//                    if (request.params != null && !request.params.isEmpty()) {
//                        for (String key : request.params.keySet()) {
//                            f.add(key, String.valueOf(request.params.get(key)));
//                        }
//                    }
                    Request.Builder builder = new Request.Builder().url(finalUrl).delete(f.build());

                    //除了登录接口不需要token,其它接口都需要token
                    SharedPreferences sp = activity.getSharedPreferences("LoginState", 0);
                    //获得登录手机号
                    token = sp.getString("token", "");
                    if (StringUtil.isEmpty(token)) {
                        token = sp.getString("onceToken", "");
                        builder.addHeader("X-Token", "" + token);
                    } else {
                        builder.addHeader("X-Token", "" + token);
                    }
                    builder.addHeader("Content-Type", "application/json");
                    Request mRequest = builder.build();
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(mRequest).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            subscriber.onError(e);

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {


                            Headers headers = response.headers();//response为okhttp请求后的响应
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionid = session.substring(0, session.indexOf(";"));
                            }
                            LogUtil.e("Response", response.toString());
                            if (response.isSuccessful()) {
                                String result = response.body().string();
                                subscriber.onNext(result);
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(new Throwable(""));
                            }
                        }
                    });
                }
            }
        });
    }


    /**
     * @param url 接口地址(无参数)
     * @param map 拼接参数集合
     * @Description get请求URL拼接参数
     */
    public static String getAppendUrl(String url, Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                if (StringUtil.isEmpty(buffer.toString())) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;

    }

    /**
     * 网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            // 打印所有的网络状态
            NetworkInfo[] infos = cm.getAllNetworkInfo();
            if (infos != null) {
                for (int i = 0; i < infos.length; i++) {
                    // Log.d("tag", "isNetworkAvailable - info: " +
                    // infos[i].toString());
                    if (infos[i].getState() == NetworkInfo.State.CONNECTED) {
                    }
                }
            }
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                Log.d("tag",
                        "isNetworkAvailable - 是否有网络： "
                                + networkInfo.isAvailable());
            } else {
//                Log.d("tag", "isNetworkAvailable - 完成没有网络！");
                return false;
            }
            // 1、判断是否有3G网络
            if (networkInfo != null
                    && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
//                Log.d("tag", "isNetworkAvailable - 有3G网络");
                return true;
            } else {
//                Log.d("tag", "isNetworkAvailable - 没有3G网络");
            }
            // 2、判断是否有wifi连接
            if (networkInfo != null
                    && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//                Log.d("tag", "isNetworkAvailable - 有wifi连接");
                return true;
            } else {
//                Log.d("tag", "isNetworkAvailable - 没有wifi连接");
            }
        }
        return false;
    }
}
